<template>
  <view class="hot-keywords-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">热门关键词分析</view>
      <view class="subtitle">{{analysisStore.timeRangeText}}搜索关键词热度排行</view>
    </view>
    
    <!-- 操作栏 -->
    <view class="action-bar">
      <view class="chart-type-switcher">
        <view 
          v-for="(item, index) in chartTypes" 
          :key="index" 
          :class="['type-item', analysisStore.filter.chartType === item.value ? 'active' : '']"
          @click="switchChartType(item.value)"
        >
          <text class="iconfont" :class="item.icon"></text>
          <text>{{item.label}}</text>
        </view>
      </view>
    </view>
    
    <!-- 关键词总览卡片 -->
    <view class="overview-card">
      <view class="overview-item">
        <text class="item-value">{{totalKeywords || '0'}}</text>
        <text class="item-label">关键词总数</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{totalSearches || '0'}}</text>
        <text class="item-label">搜索总次数</text>
      </view>
      <view class="overview-item">
        <text class="item-value">{{topKeyword || '-'}}</text>
        <text class="item-label">最热关键词</text>
      </view>
    </view>
    
    <!-- 图表区域 -->
    <view class="chart-area" v-if="!isLoading">
      <!-- 使用图表组件显示关键词热度数据 -->
      <qiun-data-charts 
        :type="chartType" 
        :chart-data="chartDataObject" 
        :loading="chartLoading"
        canvas-id="keywords-chart"
        canvas-height="350px"
      ></qiun-data-charts>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-load-more status="loading" :contentText="loadingText"></uni-load-more>
    </view>
    
    <!-- 关键词列表 -->
    <view class="keywords-list" v-else>
      <view class="section-title">热门关键词排行</view>
      
      <scroll-view scroll-y class="keywords-scroll">
        <view 
          class="keyword-item" 
          v-for="(item, index) in hotKeywords" 
          :key="index"
          @click="searchByKeyword(item.keyword)"
        >
          <view class="keyword-rank" :class="{'top1': index === 0, 'top2': index === 1, 'top3': index === 2}">
            {{index + 1}}
          </view>
          
          <view class="keyword-content">
            <text class="keyword-text">{{item.keyword}}</text>
            <text class="keyword-count">搜索{{item.count}}次</text>
          </view>
          
          <view class="keyword-bar">
            <view 
              class="keyword-progress" 
              :style="{width: (item.count / maxSearchCount * 100) + '%'}"
            ></view>
          </view>
        </view>
        
        <!-- 无数据提示 -->
        <view class="no-data" v-if="hotKeywords.length === 0">
          <text>暂无关键词数据</text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部操作区 -->
    <view class="footer-actions">
      <button class="action-btn export-btn" @click="exportData">
        <text class="iconfont icon-download"></text>
        <text>导出数据</text>
      </button>
      <button class="action-btn refresh-btn" @click="refreshData">
        <text class="iconfont icon-refresh"></text>
        <text>刷新</text>
      </button>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useAnalysisStore } from '@/store/analysis.js';
import QiunDataCharts from '@/components/qiun-data-charts/qiun-data-charts.vue';

export default {
  name: 'HotKeywords',
  components: {
    QiunDataCharts
  },
  setup() {
    // 获取分析数据仓库
    const analysisStore = useAnalysisStore();
    
    // 热门关键词数据
    const hotKeywords = ref([]);
    // 页面加载状态
    const isLoading = ref(true);
    // 图表加载状态
    const chartLoading = ref(false);
    // 图表类型
    const chartTypes = [
      { label: '柱状图', value: 'bar', icon: 'icon-bar-chart' },
      { label: '饼图', value: 'pie', icon: 'icon-pie-chart' }
    ];
    // 加载文字
    const loadingText = {
      contentdown: '上拉显示更多',
      contentrefresh: '数据加载中...',
      contentnomore: '没有更多数据了'
    };
    
    // 图表类型（依据分析store中的filter.chartType）
    const chartType = computed(() => {
      // 将store中的chartType转换为qiun-data-charts支持的类型
      switch(analysisStore.filter.chartType) {
        case 'bar': return 'column';
        case 'pie': return 'pie';
        default: return 'column';
      }
    });
    
    // 计算关键词总数
    const totalKeywords = computed(() => {
      return hotKeywords.value.length || 0;
    });
    
    // 计算搜索总次数
    const totalSearches = computed(() => {
      if (!hotKeywords.value || hotKeywords.value.length === 0) return 0;
      return hotKeywords.value.reduce((total, item) => total + item.count, 0);
    });
    
    // 获取最热门的关键词
    const topKeyword = computed(() => {
      if (!hotKeywords.value || hotKeywords.value.length === 0) return '-';
      return hotKeywords.value[0].keyword;
    });
    
    // 获取最大搜索次数（用于进度条计算）
    const maxSearchCount = computed(() => {
      if (!hotKeywords.value || hotKeywords.value.length === 0) return 1;
      return hotKeywords.value[0].count;
    });
    
    // 图表数据对象
    const chartDataObject = computed(() => {
      // 如果没有关键词数据，返回空数据结构
      if (!hotKeywords.value || hotKeywords.value.length === 0) {
        return {
          categories: [],
          series: []
        };
      }
      
      // 准备图表数据
      const result = {};
      
      // 只取前10个关键词显示在图表中，避免图表过于拥挤
      const top10 = hotKeywords.value.slice(0, 10);
      
      // 根据图表类型处理数据格式
      if (chartType.value === 'pie') {
        // 饼图不需要categories，直接构建series
        result.series = top10.map(item => ({
          name: item.keyword,
          data: item.count
        }));
      } else {
        // 柱状图需要categories和series
        // 设置分类（关键词）
        result.categories = top10.map(item => item.keyword);
        
        // 构建系列数据
        result.series = [{
          name: '搜索次数',
          data: top10.map(item => item.count)
        }];
      }
      
      return result;
    });
    
    // 页面初始化
    onMounted(() => {
      loadHotKeywordsData();
    });
    
    // 加载热门关键词数据
    async function loadHotKeywordsData() {
      isLoading.value = true;
      try {
        // 获取热门关键词数据
        const data = await analysisStore.fetchHotKeywords();
        hotKeywords.value = data || [];
      } catch (error) {
        console.error('加载热门关键词数据失败:', error);
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      } finally {
        isLoading.value = false;
      }
    }
    
    // 切换图表类型
    function switchChartType(type) {
      analysisStore.setFilter({ chartType: type });
      // 图表类型改变后会自动触发图表重绘，因为我们使用了computed
    }
    
    // 刷新数据
    function refreshData() {
      loadHotKeywordsData();
    }
    
    // 使用关键词搜索图书
    function searchByKeyword(keyword) {
      uni.navigateTo({
        url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
      });
    }
    
    // 导出数据
    function exportData() {
      const csvContent = analysisStore.exportToCSV('keywords');
      
      // 在真实环境中，这里会处理CSV导出
      // 由于小程序和H5环境的限制，这里只做简单提示
      uni.showModal({
        title: '导出成功',
        content: '在实际环境中，这里会下载热门关键词数据的CSV文件',
        showCancel: false
      });
      
      console.log('导出的CSV数据：', csvContent);
    }
    
    return {
      analysisStore,
      chartTypes,
      loadingText,
      hotKeywords,
      isLoading,
      chartLoading,
      chartType,
      chartDataObject,
      totalKeywords,
      totalSearches,
      topKeyword,
      maxSearchCount,
      switchChartType,
      refreshData,
      exportData,
      searchByKeyword
    };
  }
};
</script>

<style lang="scss">
.hot-keywords-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
  
  /* 顶部标题样式 */
  .header {
    margin-bottom: 30rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #999999;
      margin-top: 10rpx;
    }
  }
  
  /* 操作栏样式 */
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .chart-type-switcher {
      display: flex;
      
      .type-item {
        display: flex;
        align-items: center;
        margin-right: 30rpx;
        font-size: 26rpx;
        color: #666666;
        
        .iconfont {
          margin-right: 6rpx;
          font-size: 28rpx;
        }
        
        &.active {
          color: #0066ff;
          font-weight: 500;
        }
      }
    }
  }
  
  /* 关键词总览卡片样式 */
  .overview-card {
    display: flex;
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .overview-item {
      flex: 1;
      text-align: center;
      padding: 0 20rpx;
      position: relative;
      
      &:not(:last-child):after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background-color: #f0f0f0;
      }
      
      .item-value {
        font-size: 40rpx;
        color: #0066ff;
        font-weight: bold;
        display: block;
        /* 如果值太长需要截断 */
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      
      .item-label {
        font-size: 24rpx;
        color: #999999;
        margin-top: 10rpx;
        display: block;
      }
    }
  }
  
  /* 图表区域样式 */
  .chart-area {
    background-color: #ffffff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  /* 加载状态样式 */
  .loading-container {
    padding: 40rpx 0;
  }
  
  /* 关键词列表样式 */
  .keywords-list {
    background-color: #ffffff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .section-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 30rpx;
    }
    
    .keywords-scroll {
      max-height: 600rpx;
    }
    
    .keyword-item {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #f5f5f5;
      
      .keyword-rank {
        width: 50rpx;
        height: 50rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 25rpx;
        background-color: #f0f0f0;
        font-size: 26rpx;
        color: #666666;
        margin-right: 20rpx;
        
        &.top1 {
          background-color: #FF6B6B;
          color: #FFFFFF;
        }
        
        &.top2 {
          background-color: #FF9E4D;
          color: #FFFFFF;
        }
        
        &.top3 {
          background-color: #FFCA3A;
          color: #FFFFFF;
        }
      }
      
      .keyword-content {
        width: 200rpx;
        margin-right: 20rpx;
        
        .keyword-text {
          display: block;
          font-size: 28rpx;
          color: #333333;
          font-weight: 500;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .keyword-count {
          display: block;
          font-size: 22rpx;
          color: #999999;
          margin-top: 4rpx;
        }
      }
      
      .keyword-bar {
        flex: 1;
        height: 20rpx;
        background-color: #f0f0f0;
        border-radius: 10rpx;
        overflow: hidden;
        
        .keyword-progress {
          height: 100%;
          background-color: #0066ff;
          border-radius: 10rpx;
          min-width: 2%;
        }
      }
    }
    
    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      color: #999999;
      font-size: 26rpx;
    }
  }
  
  /* 底部操作区样式 */
  .footer-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    
    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 48%;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      .iconfont {
        margin-right: 10rpx;
      }
      
      &.export-btn {
        background-color: #ffffff;
        color: #0066ff;
        border: 1px solid #0066ff;
      }
      
      &.refresh-btn {
        background-color: #0066ff;
        color: #ffffff;
      }
    }
  }
}
</style>
